import { Component, OnInit } from '@angular/core';
import {
  NavigationCancel,
  NavigationEnd,
  NavigationError,
  NavigationStart,
  RouteConfigLoadEnd,
  RouteConfigLoadStart,
  Router
} from '@angular/router';
import { takeUntil } from 'rxjs';

import { DestroyService } from '@core/base';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-base-router-progress-bar',
  templateUrl: './router-progress-bar.component.html',
  styleUrls: ['./router-progress-bar.component.less'],
  providers: [DestroyService]
})
export class RouterProgressBarComponent implements OnInit {
  isFetching = false;

  constructor(private router: Router, private destroy$: DestroyService, private messageSrc: NzMessageService) {}

  ngOnInit(): void {
    this.router.events.pipe(takeUntil(this.destroy$)).subscribe(evt => {
      if (!this.isFetching && evt instanceof RouteConfigLoadStart) {
        this.isFetching = true;
      }
      if (!this.isFetching && evt instanceof NavigationStart) {
        this.isFetching = true;
      }
      if (this.isFetching && (evt instanceof NavigationError || evt instanceof NavigationCancel)) {
        this.isFetching = false;
      }
      if (this.isFetching && (evt instanceof NavigationEnd || evt instanceof RouteConfigLoadEnd)) {
        this.isFetching = false;
      }
    });
  }
}
